using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyMES.IServices.WarehouseManagement.PhysicalStocks;
using MyMES.IServices.WarehouseManagement.Codings;
using VOL.Entity.DomainModels;
using MyMES.Services.WarehouseManagement.Codings.DTOs;

namespace VOL.WebApi.Controllers.MyMES
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WarehousesController : ControllerBase
    {
        private readonly IPhysicalStockService _physicalStockService;
        private readonly ICodingService _codingService;

        public WarehousesController(
            IPhysicalStockService physicalStockService,
            ICodingService codingService)
        {
            _physicalStockService = physicalStockService;
            _codingService = codingService;
        }

        /// <summary>
        /// 获取库存现有量列表
        /// </summary>
        /// <param name="materialCode">物料编码（可选）</param>
        /// <returns>库存列表</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<List<PhysicalStock>>> GetPhysicalStockList([FromQuery] string materialCode = null)
        {
            try
            {
                // 记录请求参数
                Console.WriteLine($"GetPhysicalStockList called with materialCode: {materialCode}");

                // 调用服务获取数据
                var result = await _physicalStockService.GetPhysicalStockList(materialCode);

                // 记录返回结果数量
                Console.WriteLine($"GetPhysicalStockList returned {result.Count} records");

                // 返回结果
                return Ok(new
                {
                    success = true,
                    data = result,
                    total = result.Count
                });
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"GetPhysicalStockList error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");

                // 返回错误信息
                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "获取库存数据失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取物料分类树形结构
        /// </summary>
        /// <returns>分类树形结构</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<List<MaterialCatalog>>> GetTree()
        {
            try
            {
                // 获取所有分类数据
                var result = await _physicalStockService.GetMaterialCatalogTree();

                // 返回结果
                return Ok(new
                {
                    success = true,
                    data = result
                });
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"GetTree error: {ex.Message}");

                // 返回错误信息
                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "获取分类树形结构失败：" + ex.Message
                });
            }
        }

        #region 条码管理

        /// <summary>
        /// 获取条码管理列表
        /// </summary>
        /// <param name="queryDTO">查询参数</param>
        /// <returns>条码列表</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<BarcodeDTO>> GetBarcodeList([FromQuery] BarcodeDTO queryDTO)
        {
            try
            {
                // 记录请求参数
                Console.WriteLine($"GetBarcodeList called with parameters: Type={queryDTO.BarcodeType}, Code={queryDTO.BusinessCode}, Name={queryDTO.BusinessName}, Page={queryDTO.PageIndex}");

                // 调用服务获取数据
                var result = await _codingService.GetBarcodeListAsync(queryDTO);

                // 记录返回结果数量
                Console.WriteLine($"GetBarcodeList returned {result.Items?.Count ?? 0} records, Total={result.Total}");

                // 返回结果
                return Ok(new
                {
                    success = true,
                    data = result.Items,
                    total = result.Total,
                    pageIndex = result.PageIndex,
                    pageSize = result.PageSize,
                    totalPages = result.TotalPages
                });
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"GetBarcodeList error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");

                // 返回错误信息
                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "获取条码数据失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 更新条码信息
        /// </summary>
        /// <param name="barcode">条码信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult> UpdateBarcode([FromBody] BarcodeManagement barcode)
        {
            try
            {
                // 参数验证
                if (barcode == null || barcode.Id == 0)
                {
                    return BadRequest(new { success = false, message = "无效的条码信息" });
                }

                // 记录请求参数
                Console.WriteLine($"UpdateBarcode called for ID: {barcode.Id}");

                // 调用服务更新数据
                var result = await _codingService.UpdateBarcodeAsync(barcode);

                // 返回结果
                return Ok(new
                {
                    success = true,
                    message = "更新成功"
                });
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"UpdateBarcode error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");

                // 返回错误信息
                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "更新条码数据失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 获取条码类型列表
        /// </summary>
        /// <returns>条码类型列表</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public ActionResult<List<KeyValuePair<string, string>>> GetBarcodeTypes()
        {
            try
            {
                // 调用服务获取数据
                var result = _codingService.GetBarcodeTypes();

                // 返回结果
                return Ok(new
                {
                    success = true,
                    data = result
                });
            }
            catch (Exception ex)
            {
                // 记录错误
                Console.WriteLine($"GetBarcodeTypes error: {ex.Message}");

                // 返回错误信息
                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "获取条码类型列表失败：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 根据条码值获取完整的条码信息
        /// </summary>
        /// <param name="barcode">条码值</param>
        /// <returns>条码完整信息</returns>
        [HttpGet("GetBarcodeDetails")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<BarcodeManagement>> GetBarcodeDetails([FromQuery] string barcode)
        {
            try
            {
                if (string.IsNullOrEmpty(barcode))
                {
                    return BadRequest(new { success = false, message = "条码值不能为空" });
                }

                var result = await _codingService.GetBarcodeDetailsByValueAsync(barcode);

                return Ok(new
                {
                    success = true,
                    data = result
                });
            }
            catch (Exception ex) when (ex.Message == "未找到对应的条码信息")
            {
                return NotFound(new
                {
                    success = false,
                    message = ex.Message
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetBarcodeDetails error: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");

                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    success = false,
                    message = "获取条码详情失败：" + ex.Message
                });
            }
        }

        #endregion
    }
} 